﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Firecracker.Bootstrapper.Utils;
using Mono.Cecil;

namespace Firecracker.Bootstrapper.Interception.Intercepts
{
  [Export(typeof(IInterceptLocator))]
  public class AttributeInterceptLocator : IInterceptLocator
  {
    private AssemblyDefinition _assembly;

    public IEnumerable<InterceptDefinition> Locate()
    {
      var interceptionName = typeof(Replace).FullName;
      var x = from m in _assembly.Modules
             from t in m.Types
             from a in t.CustomAttributes
             where a.AttributeType.FullName == interceptionName
             select new InterceptDefinition
             {
               Target = (a.ConstructorArguments.First().Value as TypeReference).Resolve(),
               Replacement = t
             };
      var result = x.ToList();

      //foreach (var interceptionTarget in result)
      //{
      //  Console.WriteLine("\t" + interceptionTarget.Target);
      //  foreach (var typeDefinition in interceptionTarget.Target.GetInteritanceHierarchy())
      //  {
      //    Console.WriteLine("\t\t" + typeDefinition.FullName);
      //  }
      //}
      return result;
    }

    public void PointTo(AssemblyDefinition testAssembly)
    {
      _assembly = testAssembly;
    }
  }
}
